﻿using Common.Library;
using Common.Model;
using Dapper.Library;
using DevOps.Model;
using Network.Library;
using Redis.Library;
using Serialize.Library;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mall.Logic
{
    /// <summary>
    /// 公用操作类
    /// </summary>
    public class OperationLogicImpl
    {
        /// <summary>
        /// PC管理端添加日志记录
        /// </summary>
        /// <param name="func_type">功能类型 100：插入操作  101：更新操作 102：删除操作</param>
        /// <param name="business_title">业务标题【用户管理】</param>
        /// <param name="detail">操作明细</param>
        /// <param name="user_id">用户ID</param>
        public void AddOperationLog(OperationLogType func_type, BusinessTitleType business_title, string detail, string user_id = "")
        {
            string clientIp = HttpHelper.GetIP();
            Task.Run(() =>
            {
                var user = GetLoginUserInfo(user_id);
                using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
                {
                    SysOperationLogInfoEntity logInfoEntity = new SysOperationLogInfoEntity
                    {
                        service_name = ServiceName.DevOpsService.GetEnumItemDescription(),
                        business_title = business_title.GetEnumItemDescription(),
                        detail = detail,
                        func_type = (int)func_type,
                        ip_address = clientIp,
                        user_code = user.id,
                        user_name = user.realname
                    };
                    var result = con.CommandSet<SysOperationLogInfoEntity>().InsertAsync(logInfoEntity);
                }
            });
        }

        /// <summary>
        /// 获取登录人员信息
        /// </summary>
        /// <returns></returns>
        public UserLoginInfo GetLoginUserInfo(string user_id = "")
        {
            var resultInfo = new UserLoginInfo();
            string userId = string.Empty;
            if (user_id.IsNullOrEmpty())
            {
                userId = HttpHelper.GetJwtUserId();
            }
            else
            {
                userId = user_id;
            }
            string userStr = RedisClient.GetRedisDb(RedisAuthorityInfo.RedisDbWeb).StringGet(RedisAuthorityInfo.RedisSessionCode + userId);
            if (!string.IsNullOrEmpty(userStr))
            {
                resultInfo = JsonHelper.JsonToObject<UserLoginInfo>(userStr);
            }
            return resultInfo;
        }

    }
}
